<template>
  <div class="file-manager">
    <!-- Left Sidebar -->
    <div class="sidebar" v-loading="loadingLeft">
      <div class="folder-list" >
        <!-- 递归渲染文件夹 -->
        <FolderItem v-loading="loadingLeft" v-for="folder in documentTree" :key="folder.ID" :folder="folder" :active-folder-id="activeFolderId"
          @select-folder="handleSelectFolder" @add-folder="handleAddFolder" @edit-folder="handleEditFolder"
          @delete-folder="handleDeleteFolder" />
      </div>
    </div>

    <!-- Main Content -->
    <div class="main-content">
      <div class="toolbar">
        <div class="toolbar-left">
          <!-- 直接上传文件，无需弹窗 -->
          <el-upload
            :action="uploadFileUrl"
            :on-success="handleUploadSuccess"
            :headers="uploadHeaders"
            :data="uploadFileData"
            :before-upload="beforeUpload"
            :show-file-list="false"
          >
            <el-button type="primary" class="upload-button">
              <el-icon class="button-icon">
                <Upload />
              </el-icon>
              上传文件
            </el-button>
          </el-upload>
        </div>
        <div class="toolbar-right">
          <el-input v-model="searchQuery" placeholder="搜索文件" class="search-input">
            <template #prefix>
              <el-icon class="search-icon">
                <Search />
              </el-icon>
            </template>
          </el-input>
        </div>
      </div>
      <div class="tableBar" v-loading="loadingRight">
        <el-table :data="tableData" class="file-table" :default-sort="{ prop: 'createAt', order: 'descending' }">
          <!-- <el-table-column type="selection" width="55" /> -->
          <el-table-column label="文件名" min-width="280">
            <template #default="scope">
              <div class="file-name">
                <el-icon class="file-icon" v-if="scope.row.type === 'docx'">
                  <Document />
                </el-icon>
                <el-icon class="file-icon" v-else-if="scope.row.type === 'xlsx'">
                  <Document />
                </el-icon>
                {{ scope.row.name }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="createUserName" label="创建人" width="100" align="center"/>
          <el-table-column prop="createAt" label="创建时间" width="160" align="center" sortable :sort-method="sortByCreateAt"/>
          <el-table-column prop="updateAt" label="修改时间" width="160" align="center"/>
          <el-table-column prop="size" label="大小" width="100" align="center" />
          <el-table-column label="操作" width="160" align="center">
            <template #default="scope">
              <el-button type="primary" size="small">
                  <el-icon @click="handlePreviewDocument(scope.row.url)">
                   查看
                  </el-icon>
              </el-button>
              <el-button type="success" size="small">
                <el-icon @click="handleDownloadFile(handleFileName(scope.row.url), baseUrl)">
                  下载
                </el-icon>
              </el-button>
              <el-button type="danger" size="small">
                <el-icon @click="handleDeleteFile(scope.row)">
                  删除
                </el-icon>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>


  <!-- 修改文件夹模态框 -->
  <el-dialog v-model="editFolderDialogVisible" title="修改文件夹" width="30%" :close-on-click-modal="false">
    <el-form :model="editFolderForm" label-width="80px">
      <el-form-item label="文件夹名称">
        <el-input v-model="editFolderForm.title" placeholder="请输入文件夹名称" />
      </el-form-item>
      <el-form-item label="描述">
        <el-input v-model="editFolderForm.description" placeholder="请输入描述" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="editFolderDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmEditFolder">确定</el-button>
      </span>
    </template>
  </el-dialog>

  

  <!-- 新建文件夹模态框 -->
  <el-dialog v-model="addFolderDialogVisible" title="新建文件夹" width="30%" :close-on-click-modal="false">
    <el-input v-model="newFolderName" placeholder="请输入文件夹名称" />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="addFolderDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAddFolder">确定</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 预览文件（已禁用占位） -->
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue';
import {
  Document,
  Upload,
  Search,
} from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { GetDocumentTree, PostCreatDocumentTree, DeleteDocumentTree, PutUpdateDocumentTreeName, PostUploadDocumentTreeFile, GetDocumentTreeFiles, DeleteFileById } from "@/api/files/index";
import FolderItem from './FolderItem.vue'; // 引入 FolderItem 组件
import { handleDownloadFile, handleFileName, openPreviewInNewWindow } from "@/utils/utils";

interface Folder {
  ID: number;
  label: string;
  description?: string; // 添加 description 属性，可选
  children: Folder[];
}

interface File {
  name: string;
  type: string;
  createAt: string;
  updateAt: string;
  size: string;
}

// const baseUrl = ref(import.meta.env.VITE_SERVE);
const baseUrl = ref("");
const loadingLeft = ref(false);
const loadingRight = ref(false);
const searchQuery = ref('');
const documentTree = ref<Folder[]>([]);
const activeFolderId = ref<any>(null);
const addFolderDialogVisible = ref(false);
const newFolderName = ref('');
const selectedParentId = ref<number | null>(null);
const tableData = ref<File[]>([]);
const editFolderDialogVisible = ref(false);
const uploadFileDialogVisible = ref(false); // 已废弃：不再弹出
const uploadFileUrl = ref('/saferycom/file/upload_file'); // 文件上传的接口地址
// 获取 token
const token = localStorage.getItem('TOKEN') || '';
const editFolderForm = ref({
  id: null as number | null, // 允许 id 为 number 或 null
  title: '',
  description: '',
});

// 上传文件的请求头
const uploadHeaders = ref({
  token: token, // 携带 token
});

// 上传文件的额外参数（随选择的文件夹动态携带）
const uploadFileData = ref({
  fileType: 'managerFiles',
  fileTypeId: 5,
});



// 获取指定文件夹下的文件列表
const fetchFilesByFolderId = async (folderId: number) => {
  try {
    loadingRight.value = true;
    const { data } = await GetDocumentTreeFiles(folderId);
    if (data.code === 200) {
      // 将接口返回的数据映射为 tableData 的结构
      tableData.value = data.data.map((file: any) => ({
        name: file.file_name,
        type: file.file_url.split('.').pop(), // 获取文件类型
        createAt: file.createAt,
        updateAt: file.UpdatedAt,
        size: file.file_size,
        id: file.ID,
        documentID: file.documentID,
        createUserName: file.file_name_user_name,
        url: file.file_url,
      }));
      loadingRight.value = false;
    } else {
      ElMessage.error(data.msg || '获取文件列表失败');
      loadingRight.value = false;
    }
  } catch (error) {
    ElMessage.error('获取文件列表失败');
    loadingRight.value = false;
  }
};

// 过滤文件列表
const filteredTableData = computed(() => {
  if (!searchQuery.value) return tableData.value;
  return tableData.value.filter((file) =>
    file.name.toLowerCase().includes(searchQuery.value.toLowerCase())
  );
});

// 创建时间排序方法（列自定义）
const sortByCreateAt = (a: any, b: any) => {
  const at = new Date(a.createAt).getTime();
  const bt = new Date(b.createAt).getTime();
  return at - bt;
};

// 获取文档树
const fetchDocumentTree = async () => {
  try {
    loadingLeft.value = true;
    const { data } = await GetDocumentTree();
    if (data.code === 200) {
      documentTree.value = data.data;
      loadingLeft.value = true;
    } else {
      ElMessage.error(data.msg || '获取文档树失败');
      loadingLeft.value = false;
    }
    loadingLeft.value = false;
  } catch (error) {
    ElMessage.error('获取文档树失败');
    loadingLeft.value = false;
  }
};


// 删除单个文件
const handleDeleteFile = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定要删除该文件吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    const { data } = await DeleteFileById(row.id);
    if (data.code == 200) {
      ElMessage.success(data.msg);
      fetchFilesByFolderId(row.documentID);
    } else {
      ElMessage.error(data.msg);
    }
  } catch (error) {
    // 用户点击取消或请求失败
    if (error !== 'cancel' && error !== 'close') {
      ElMessage.error('删除文件失败');
    }
  }
};



// 上传前校验：必须先选择文件夹，同时动态补充上传额外参数
const beforeUpload = () => {
  if (!activeFolderId.value) {
    ElMessage.warning('请先选择一个文件夹');
    return false;
  }
  // 将当前文件夹信息追加到表单
  uploadFileData.value = {
    ...uploadFileData.value,
    id: activeFolderId.value,
  } as any;
  return true;
};

// 文件上传前的校验
// const beforeUpload = (file: File) => {
//   const isAllowed = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; // 只允许上传 .xlsx 文件
//   if (!isAllowed) {
//     ElMessage.error('只能上传 .xlsx 文件');
//   }
//   return isAllowed;
// };

// 文件上传成功后的处理
const handleUploadSuccess = (response: any, file: File) => {
  if (response.code === 200) {
    ElMessage.success('文件上传成功');
    // 调用接口，传递当前文件夹的 ID 和文件路径
    uploadFileToServer(response.data.resultFilePath);
    // 上传成功后刷新当前文件夹文件列表
    if (activeFolderId.value) fetchFilesByFolderId(activeFolderId.value);
  } else {
    ElMessage.error(response.msg || '文件上传失败');
  }
};

// 调用接口上传文件
const uploadFileToServer = async (filePath: string) => {
  try {
    const { data } = await PostUploadDocumentTreeFile({
      id: activeFolderId.value,
      filePath: filePath,
    });
    if (data.code === 200) {
      ElMessage.success('文件上传成功');
      uploadFileDialogVisible.value = false;
    } else {
      ElMessage.error(data.msg || '文件上传失败');
    }
  } catch (error) {
    ElMessage.error('文件上传失败');
  }
};
// 处理文件夹选择
const handleSelectFolder = (folder: Folder) => {
  activeFolderId.value = folder.ID;
  fetchFilesByFolderId(folder.ID); // 获取该文件夹下的文件列表
};


// 处理修改文件夹
const handleEditFolder = (folder: Folder) => {
  // 打开模态框，并初始化表单数据
  editFolderForm.value = {
    id: folder.ID, // ID 是 number 类型
    title: folder.label,
    description: folder.description || '', // 如果 description 不存在，使用默认值 ''
  };
  editFolderDialogVisible.value = true;
};


// 确认修改文件夹
const confirmEditFolder = async () => {
  if (!editFolderForm.value.title) {
    ElMessage.warning('请输入文件夹名称');
    return;
  }

  try {
    // 调用修改接口
    const { data } = await PutUpdateDocumentTreeName({
      id: editFolderForm.value.id,
      title: editFolderForm.value.title,
      description: editFolderForm.value.description,
    });

    if (data.code === 200) {
      ElMessage.success('修改文件夹成功');
      editFolderDialogVisible.value = false;
      fetchDocumentTree(); // 刷新文件夹树
    } else {
      ElMessage.error(data.msg || '修改文件夹失败');
    }
  } catch (error) {
    ElMessage.error('修改文件夹失败');
  }
};


// 处理添加文件夹
const handleAddFolder = (folder: Folder) => {
  // 记录点击的文件夹用于新增
  selectedParentId.value = folder.ID; // 记录点击“+”按钮的文件夹 ID
  addFolderDialogVisible.value = true; // 显示模态框
};

// 确认添加文件夹
const confirmAddFolder = async () => {
  if (!newFolderName.value) {
    ElMessage.warning('请输入文件夹名称');
    return;
  }

  try {
    const { data } = await PostCreatDocumentTree({
      parentId: selectedParentId.value,
      title: newFolderName.value,
      description: '管理项目的所有文件',
    });

    if (data.code === 200) {
      ElMessage.success('新建文件夹成功');
      addFolderDialogVisible.value = false;
      newFolderName.value = '';
      fetchDocumentTree(); // 刷新文件夹树
    } else {
      ElMessage.error(data.msg || '新建文件夹失败');
    }
  } catch (error) {
    ElMessage.error('新建文件夹失败');
  }
};

// 处理删除文件夹
// 处理删除文件夹
const handleDeleteFolder = async (folder: Folder) => {
  try {
    // 确认删除
    await ElMessageBox.confirm(`确定要删除文件夹 "${folder.label}" 吗？`, '提示', {
      type: 'warning',
    });

    // 调用删除接口
    const { data } = await DeleteDocumentTree(folder.ID);
    if (data.code === 200) {
      ElMessage.success('删除文件夹成功');
      fetchDocumentTree(); // 刷新文件夹树
    } else {
      ElMessage.error(data.msg || '删除文件夹失败');
    }
  } catch (error) {
    // 用户取消删除
  }
};

// TODO 预览文件
const handlePreviewDocument = (url: string) => {
  console.log(baseUrl.value);
  let file = handleFileName(url);
  if (file.url.includes('Img') || file.url.includes('.pdf') || file.url.includes('.txt') || file.url.includes('.png') || file.url.includes('.gif') || file.url.includes('.jpge')) {
    // window.open(`${'http://58.215.200.58:11111' + url}`, '_blank');
    // window.open(`${baseUrl.value + url}`, '_blank');
    // window.open(`${import.meta.env.VITE_SERVE + url}`, '_blank');
    window.open(`${'http://192.168.0.91:19081' + url}`, '_blank');
    return;
  } else {
    openPreviewInNewWindow( url, file.fileName);
  }
};


// 组件挂载时获取数据
onMounted(() => {
  fetchDocumentTree();
  // fetchFilesByFolderId(1);
});
</script>

<style lang="scss" scoped>
.file-manager {
  display: flex;
  height: 100%;
  background: #fff;
  .sidebar {
    min-width: 350px;
    height: 100%;
    border-right: 1px solid #e5e7eb;
    padding: 5px;
    overflow: auto;
    font-size: 13px;
    .folder-list {
      .folder-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0.5rem;
        color: #4b5563;
        border-radius: 0.375rem;
        cursor: pointer;
        &:hover {
          background-color: #f3f4f6;
        }

        &.active {
          background-color: #eff6ff;
        }

        .folder-item-content {
          display: flex;
          align-items: center;
          .folder-icon {
            margin-right: 0.5rem;
            transition: transform 0.2s;

            &.rotate-90 {
              transform: rotate(90deg);
            }
          }
        }
      }

      .sub-folder-list {
        margin-left: 0.5rem;
      }
    }
  }

  .main-content {
    flex: 1;
    width: calc(100% - 350px);
    padding: 10px;
    height: 100%;
    .toolbar {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 1.5rem;

      .toolbar-left {
        display: flex;
        align-items: center;
        gap: 1rem;

        .upload-button,
        .new-folder-button {
          display: flex;
          align-items: center;

          .button-icon {
            margin-right: 0.5rem;
          }
        }
      }

      .toolbar-right {
        .search-input {
          width: 16rem;
        }
      }
    }
    .tableBar {
      height: calc(100% - 60px);
      overflow: auto;
    }
    .file-table {
      .file-name {
        display: flex;
        align-items: center;

        .file-icon {
          margin-right: 0.5rem;
        }
      }

      .file-actions {
        display: flex;
        align-items: center;
        gap: 0.75rem;

        .action-icon {
          cursor: pointer;
          color: #3b82f6;

          &:hover {
            color: #2563eb;
          }
        }

        .delete-icon {
          color: #ef4444;

          &:hover {
            color: #dc2626;
          }
        }
      }
    }
  }
}
</style>
